local extension = Package("skpojun")
extension.extensionName = "jilvRem"

local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["skpojun"] = "极略三国-破军",
}

local yujin = General(extension, "sk__yujin", "wei", 4)
local sk__zhengyi = fk.CreateViewAsSkill{
  name = "sk__zhengyi",
  pattern = ".|.|.|.|.|basic",
  prompt = function()
    if Self:getHandcardNum() < Self.hp then
      return "#sk__zhengyi-draw"
    else
      return "#sk__zhengyi-discard"
    end
  end,
  interaction = function(self,player)
    local all_names = U.getAllCardNames("b")
    local names = U.getViewAsCardNames(player, self.name, all_names)
    return U.CardNameBox {choices = names, all_choices = all_names,}
  end,
  card_filter = function (self, to_select, selected,player)
    if player:getHandcardNum() < player.hp then
      return false
    else
      return #selected == 0 and Fk:currentRoom():getCardArea(to_select) == Card.PlayerHand and not player:prohibitDiscard(to_select)
    end
  end,
  before_use = function (self, player, use)
    local id = use.card:getMark(self.name)
    if id == 0 then
      player:drawCards(1, self.name)
    elseif id ~= 0 and table.contains(player:getCardIds("h"), id) then
      player.room:throwCard(id, self.name, player, player)
    end
  end,
  view_as = function(self, cards,player)
    if not self.interaction.data then return end
    local card = Fk:cloneCard(self.interaction.data)
    if player:getHandcardNum() > player.hp then
      if #cards ~= 1 then return end
      card:setMark(self.name, cards[1])
    end
    card.skillName = self.name
    return card
  end,
  enabled_at_play = function(self, player)
    return math.abs(player:getHandcardNum() - math.max(player.hp, 0)) == 1
  end,
  enabled_at_response = function(self, player, response)
    return not response and math.abs(player:getHandcardNum() - math.max(player.hp, 0)) == 1
  end,
}
yujin:addSkill(sk__zhengyi)
Fk:loadTranslationTable{
  ["sk__yujin"] = "于禁",
  ["#sk__yujin"] = "弗克其终",

  ["sk__zhengyi"] = "整毅",
  [":sk__zhengyi"] = "当你需要使用基本牌时，你可以弃置一张手牌或摸一张牌以令你的手牌数等于体力值，视为使用之。",
  ["#sk__zhengyi-draw"] = "整毅：你可以摸一张牌，视为使用基本牌",
  ["#sk__zhengyi-discard"] = "整毅：你可以弃一张手牌，视为使用基本牌",

  ["$sk__zhengyi1"] = "兵刃相接，汝当片甲不留！",
  ["$sk__zhengyi2"] = "厉兵秣马，枕戈待敌。",
  ["~sk__yujin"] = "",
}

local guanxing = General(extension, "sk__guanxing", "shu", 4)
local sk__yongji = fk.CreateTriggerSkill{
  name = "sk__yongji",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.Damage},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and data.card and data.card.trueName == "slash" and player.phase == Player.Play
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local e = room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
    if e then
      if e.data[1].from == player.id and e.data[1].card.trueName == "slash" and not e.data[1].extraUse then
        player:addCardUseHistory("slash", -1)
        e.data[1].extraUse = true
      end
    end
    if player:isWounded() then
      player:drawCards(math.min(player:getLostHp(), 3), self.name)
    end
  end,
}
local sk__wuzhi = fk.CreateTriggerSkill{
  name = "sk__wuzhi",
  frequency = Skill.Compulsory,
  anim_type = "negative",
  events = {fk.EventPhaseStart},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.phase == Player.Finish and player:getMark("sk__wuzhi-turn") > 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:damage{
      to = player,
      damage = 1,
      skillName = self.name,
    }
    if player.dead then return end
    local card = room:getCardsFromPileByRule("slash", 1, "drawPile")
    if #card > 0 then
      room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonJustMove, self.name, nil, true, player.id)
    end
  end,

  refresh_events = {fk.EventPhaseEnd},
  can_refresh = function(self, event, target, player, data)
    return target == player and player:hasSkill(self, true) and player.phase == Player.Play
  end,
  on_refresh = function(self, event, target, player, data)
    local card = Fk:cloneCard("slash")
    local slash_skill = card.skill
    local status_skills = Fk:currentRoom().status_skills[TargetModSkill] or Util.DummyTable
    for _, skill in ipairs(status_skills) do
      if skill:bypassTimesCheck(player, slash_skill, Player.HistoryPhase, card, nil) then return true end
    end
    if player:usedCardTimes("slash", Player.HistoryPhase) < slash_skill:getMaxUseTime(player, Player.HistoryPhase, card, nil) then
      player.room:setPlayerMark(player, "sk__wuzhi-turn", 1)
    end
  end,
}
guanxing:addSkill(sk__yongji)
guanxing:addSkill(sk__wuzhi)
Fk:loadTranslationTable{
  ["sk__guanxing"] = "关兴",
  ["#sk__guanxing"] = "",

  ["sk__yongji"] = "勇继",
  [":sk__yongji"] = "锁定技，当你于出牌阶段内使用【杀】造成伤害后，你摸X张牌并令此【杀】不计入次数限制（X为你已损失的体力且至多为3）。",
  ["sk__wuzhi"] = "武志",
  [":sk__wuzhi"] = "锁定技，结束阶段，若你于本回合出牌阶段使用【杀】的次数小于次数上限，你受到1点伤害并从牌堆随机获得一张【杀】。",

  ["$sk__yongji1"] = "不留余勇，竭力杀敌！",
  ["$sk__yongji2"] = "逆贼宵小，拿命来！",
  ["$sk__wuzhi"] = "杀意不减，武魂不息！",
  ["~sk__guanxing"] = "父魂……何在……",
}

local guansuo = General(extension, "sk__guansuo", "shu", 4)
local sk__zhengnan = fk.CreateActiveSkill{
  name = "sk__zhengnan",
  anim_type = "offensive",
  card_num = 0,
  target_num = 1,
  prompt = "#sk__zhengnan",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0
  end,
  card_filter = Util.FalseFunc,
  target_filter =function (self, to_select, selected, selected_cards, card, extra_data, player)
    return #selected == 0 and not Fk:currentRoom():getPlayerById(to_select):prohibitUse(Fk:cloneCard("savage_assault"))
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local card = Fk:cloneCard("savage_assault")
    card.skillName = self.name
    local extra_data = {}
    extra_data.sk__zhengnan = {player.id, target.id}
    local use = {
      from = target.id,
      card = card,
      extra_data = extra_data,
    }
    room:useCard(use)
  end,
}
local sk__zhengnan_delay = fk.CreateTriggerSkill{
  name = "#sk__zhengnan_delay",
  mute = true,
  events = {fk.Damage},
  can_trigger = function(self, event, target, player, data)
    if data.card and table.contains(data.card.skillNames, "sk__zhengnan") then
      local e = player.room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
      if e then
        local use = e.data[1]
        return use.extra_data and use.extra_data.sk__zhengnan and use.extra_data.sk__zhengnan[2] == player.id
      end
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local src
    local e = room.logic:getCurrentEvent():findParent(GameEvent.UseCard)
    if e then
      local use = e.data[1]
      if use.extra_data and use.extra_data.sk__zhengnan and use.extra_data.sk__zhengnan[2] == player.id then
        src = room:getPlayerById(use.extra_data.sk__zhengnan[1])
      end
    end
    if src and not src.dead then
      src:drawCards(1, "sk__zhengnan")
    end
    if not player.dead then
      player:drawCards(1, "sk__zhengnan")
    end
  end,
}
local sk__tongxin = fk.CreateTriggerSkill{
  name = "sk__tongxin",
  anim_type = "defensive",
  frequency = Skill.Limited,
  events = {fk.AskForPeaches},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player.dying and player:usedSkillTimes(self.name, Player.HistoryGame) == 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if player:isWounded() then
      room:recover({
        who = player,
        num = math.min(2, player.maxHp) - player.hp,
        recoverBy = player,
        skillName = self.name,
      })
    end
    local generals = {}
    for _, str in ipairs({"guansuo", "baosanniang"}) do
      if not table.find(player.room.players, function(p)
        return string.find(p.general, str) or string.find(p.deputyGeneral, str)
      end) then
        for name, general in pairs(Fk.generals) do
          if general.package.extensionName ~= "hegemony" and string.find(name, str) then
            table.insert(generals, name)
          end
        end
      end
    end
    if #generals == 0 then return end
    local result = room:askForCustomDialog(player, self.name, "packages/utility/qml/ChooseGeneralsAndChoiceBox.qml", {
      generals,
      {"OK"},
      "#sk__tongxin-choose",
      {"Cancel"},
    })
    local general = ""
    if result == "" then
      return
    else
      local reply = json.decode(result)
      if reply.choice == "OK" then
        general = reply.cards[1]
      else
        return
      end
    end
    table.removeOne(room.general_pile, general)
    local isDeputy, kingdomChange = false, "shu"
    if player.deputyGeneral ~= nil and (player.deputyGeneral == "sk__guansuo" or player.deputyGeneral == "baosanniang") then
      isDeputy = true
      kingdomChange = player.kingdom
    end
    room:changeHero(player, general, false, isDeputy, true, false, kingdomChange)
  end,
}
sk__zhengnan:addRelatedSkill(sk__zhengnan_delay)
guansuo:addSkill(sk__zhengnan)
guansuo:addSkill(sk__tongxin)
Fk:loadTranslationTable{
  ["sk__guansuo"] = "关索",
  ["#sk__guanxing"] = "",

  ["sk__zhengnan"] = "征南",
  [":sk__zhengnan"] = "出牌阶段限一次，你可以选择一名角色，视为其使用【南蛮入侵】，当此牌造成伤害后，你与其各摸一张牌。",
  ["sk__tongxin"] = "同心",
  [":sk__tongxin"] = "限定技，当你处于濒死状态时，你可以回复体力至2点，然后你可以将武将牌替换为（未加入游戏的）关索或鲍三娘。",
  ["#sk__zhengnan"] = "征南：令一名角色视为使用【南蛮入侵】，造成伤害后你与其各摸一张牌",
  ["#sk__tongxin-choose"] = "同心：你可以变身为关索或鲍三娘！",

  ["$sk__zhengnan1"] = "征讨南中，解大汉之患！",
  ["$sk__zhengnan2"] = "蛮夷可抚不可剿。",
  ["$sk__tongxin1"] = "携手同心，定平蛮夷。",
  ["$sk__tongxin2"] = "三娘，助我一臂之力。",
  ["~sk__guansuo"] = "天下未平，我意难平……",
}

local baosanniang = General(extension, "sk__baosanniang", "shu", 3, 3, General.Female)
local sk__jianwu = fk.CreateTriggerSkill{
  name = "sk__jianwu",
  anim_type = "offensive",
  frequency = Skill.Compulsory,
  events = {fk.AfterCardUseDeclared},
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(self) and player:getMark("@@sk__jianwu") > 0 and data.card.trueName == "slash"
  end,
  on_use = function(self, event, target, player, data)
    player.room:setPlayerMark(player, "@@sk__jianwu", 0)
    if not data.extraUse then
      player:addCardUseHistory(data.card.trueName, -1)
      data.extraUse = true
    end
  end,

  refresh_events = {fk.EventLoseSkill, fk.CardUseFinished},
  can_refresh = function(self, event, target, player, data)
    if target == player then
      if event == fk.EventLoseSkill then
        return data == self
      else
        return player:hasSkill(self)
      end
    end
  end,
  on_refresh = function(self, event, target, player, data)
    if event == fk.EventLoseSkill then
      player.room:setPlayerMark(player, "@@sk__jianwu", 0)
    else
      player.room:setPlayerMark(player, "@@sk__jianwu", data.card.type == Card.TypeBasic and 1 or 0)
    end
  end,
}
local sk__jianwu_targetmod = fk.CreateTargetModSkill{
  name = "#sk__jianwu_targetmod",
  bypass_times = function(self, player, skill, scope)
    return player:hasSkill(sk__jianwu) and skill.trueName == "slash_skill" and player:getMark("@@sk__jianwu") > 0 and
      scope == Player.HistoryPhase
  end,
  bypass_distances = function(self, player, skill)
    return player:hasSkill(sk__jianwu) and skill.trueName == "slash_skill" and player:getMark("@@sk__jianwu") > 0
  end,
  extra_target_func = function(self, player, skill)
    if player:hasSkill(sk__jianwu) and skill.trueName == "slash_skill" and player:getMark("@@sk__jianwu") > 0 then
      return 1
    end
  end,
}
local sk__zhennan = fk.CreateTriggerSkill{
  name = "sk__zhennan",
  anim_type = "offensive",
  events = {fk.TargetSpecified},
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(self) and (data.card.trueName == "slash" or data.card:isCommonTrick()) and data.firstTarget and
      #AimGroup:getAllTargets(data.tos) > 1 and player:usedSkillTimes(self.name, Player.HistoryTurn) == 0
  end,
  on_cost = function(self, event, target, player, data)
    local to = player.room:askForChoosePlayers(player, AimGroup:getAllTargets(data.tos), 1, 1,
      "#sk__zhennan-choose", self.name, true)
    if #to > 0 then
      self.cost_data = to[1]
      return true
    end
  end,
  on_use = function(self, event, target, player, data)
    player.room:damage{
      from = player,
      to = player.room:getPlayerById(self.cost_data),
      damage = 1,
      skillName = self.name,
    }
  end,
}
sk__jianwu:addRelatedSkill(sk__jianwu_targetmod)
baosanniang:addSkill(sk__jianwu)
baosanniang:addSkill(sk__zhennan)
baosanniang:addSkill("sk__tongxin")
Fk:loadTranslationTable{
  ["sk__baosanniang"] = "鲍三娘",
  ["#sk__baosanniang"] = "",

  ["sk__jianwu"] = "剑舞",
  [":sk__jianwu"] = "锁定技，若你使用的上一张牌是基本牌，你使用【杀】无距离和次数限制，且目标上限+1。",
  ["sk__zhennan"] = "镇南",
  [":sk__zhennan"] = "每回合限一次，当一名角色使用【杀】或锦囊牌指定目标后，若目标数大于1，你可以对其中一名目标角色造成1点伤害。",
  ["@@sk__jianwu"] = "剑舞",
  ["#sk__zhennan-choose"] = "镇南：你可以对一名目标角色造成1点伤害",

  ["$sk__jianwu1"] = "随夫轻剑舞，破敌万千军。",
  ["$sk__jianwu2"] = "剑舞灵动，威震南中。",
  ["$sk__zhennan1"] = "愿随夫君，同镇这南中之地。",
  ["$sk__zhennan2"] = "休想扰乱这里的清净！",
  ["$sk__tongxin_sk__baosanniang1"] = "携手同心，定平蛮夷。",
  ["$sk__tongxin_sk__baosanniang2"] = "夫君，请和我在一起。",
  ["~sk__baosanniang"] = "花落终别离……",
}

local caoxiu = General(extension, "sk__caoxiu", "wei", 4)
local sk__taoxi = fk.CreateActiveSkill{
  name = "sk__taoxi",
  anim_type = "control",
  card_num = 0,
  target_num = 0,
  prompt = "#sk__taoxi",
  can_use = function(self, player)
    return player:usedSkillTimes(self.name, Player.HistoryPhase) == 0 and
      table.find(Fk:currentRoom().alive_players, function(p) return p ~= player and not p:isKongcheng() end)
  end,
  card_filter = Util.FalseFunc,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local targets = room:getOtherPlayers(player)
    room:doIndicate(player.id, table.map(targets, Util.IdMapper))
    local mark = player:getTableMark("sk__taoxi-phase")
    for _, target in ipairs(targets) do
      if player.dead then return end
      if not target.dead and not target:isKongcheng() then
        local card = room:askForCardChosen(player, target, "h", self.name, "#sk__taoxi-card::"..target.id)
        table.insert(mark, {target.id, card})
        room:moveCardTo(card, Card.PlayerHand, player, fk.ReasonPrey, self.name, nil, false, player.id,
          {"@sk__taoxi-phase", Fk:translate(target.general)})
      end
    end
    if not player.dead then
      room:setPlayerMark(player, "sk__taoxi-phase", mark)
    end
  end,
}
local sk__taoxi_delay = fk.CreateTriggerSkill{
  name = "#sk__taoxi_delay",
  mute = true,
  events = {fk.EventPhaseEnd},
  can_trigger = function(self, event, target, player, data)
    if target == player and player:usedSkillTimes("sk__taoxi", Player.HistoryPhase) > 0 then
      local mark = player:getTableMark("sk__taoxi-phase")
      for _, info in ipairs(mark) do
        local to = player.room:getPlayerById(info[1])
        if not to.dead and table.contains(player:getCardIds("h"), info[2]) then
          return true
        end
      end
    end
  end,
  on_cost = Util.TrueFunc,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local mark = player:getTableMark("sk__taoxi-phase")
    for _, info in ipairs(mark) do
      if player.dead then return end
      local to = room:getPlayerById(info[1])
      if not to.dead and table.contains(player:getCardIds("h"), info[2]) then
        room:moveCardTo(info[2], Card.PlayerHand, to, fk.ReasonGive, "sk__taoxi", nil, false, player.id)
      end
    end
  end,
}
sk__taoxi:addRelatedSkill(sk__taoxi_delay)
caoxiu:addSkill(sk__taoxi)
Fk:loadTranslationTable{
  ["sk__caoxiu"] = "曹休",
  ["#sk__caoxiu"] = "",

  ["sk__taoxi"] = "讨袭",
  [":sk__taoxi"] = "出牌阶段限一次，你可以获得所有其他角色各一张手牌，此阶段结束时，你交还剩余的牌。",
  ["#sk__taoxi"] = "讨袭：获得所有其他角色各一张手牌，本阶段结束时归还",
  ["#sk__taoxi-card"] = "讨袭：获得 %dest 的一张手牌，本阶段结束时归还",
  ["@sk__taoxi-phase"] = "讨袭",
  ["#sk__taoxi_delay"] = "讨袭",

  ["$sk__taoxi1"] = "讨贼，须出其不意。",
  ["$sk__taoxi2"] = "就凭你，是斗不过我的。",
  ["~sk__caoxiu"] = "孤军深入，是我太轻敌了……",
}

local caojie = General(extension, "sk__caojie", "qun", 3, 3, General.Female)
local sk__huaibi = fk.CreateTriggerSkill{
  name = "sk__huaibi",
  anim_type = "defensive",
  derived_piles = "sk__caojie_xi",
  frequency = Skill.Compulsory,
  events = {fk.GameStart, fk.EventPhaseStart, fk.PreCardEffect},
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(self) then
      if event == fk.GameStart then
        return #player:getPile("sk__caojie_xi") == 0
      elseif event == fk.EventPhaseStart then
        return target == player and player.phase == Player.Finish and #player:getPile("sk__caojie_xi") == 0
      else
        return #player:getPile("sk__caojie_xi") > 0 and data.from ~= player.id and data.to == player.id and
          (data.card.trueName == "slash" or data.card:isCommonTrick()) and
          data.card.suit ~= Card.NoSuit and data.card.suit == Fk:getCardById(player:getPile("sk__caojie_xi")[1]).suit
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    if event == fk.GameStart or event == fk.EventPhaseStart then
      player:drawCards(2, self.name)
      if player.dead or player:isKongcheng() then return end
      local card = room:askForCard(player, 1, 1, false, self.name, false, ".", "#sk__huaibi-card")
      player:addToPile("sk__caojie_xi", card, true, self.name, player.id)
    else
      return true
    end
  end,
}
local sk__zhixi = fk.CreateActiveSkill{
  name = "sk__zhixi",
  anim_type = "offensive",
  card_num = 1,
  target_num = 1,
  prompt = "#sk__zhixi",
  expand_pile = "sk__caojie_xi",
  can_use = function(self, player)
    return #player:getPile("sk__caojie_xi") > 0
  end,
  target_filter =function (self, to_select, selected, selected_cards, card, extra_data, player)
    return #selected == 0 and to_select ~= player.id
  end,
  card_filter = function(self, to_select, selected,player)
    return #selected == 0 and player:getPileNameOfId(to_select) == "sk__caojie_xi"
  end,
  on_use = function(self, room, effect)
    local player = room:getPlayerById(effect.from)
    local target = room:getPlayerById(effect.tos[1])
    local mark = player:getTableMark(self.name)
    local n = 1
    if table.insertIfNeed(mark, target.id) then
      n = 3
      room:setPlayerMark(player, self.name, mark)
    end
    room:moveCardTo(effect.cards, Card.PlayerHand, target, fk.ReasonGive, self.name, nil, true, player.id)
    if not target.dead then
      room:loseHp(target, n, self.name)
    end
  end,
}
caojie:addSkill(sk__huaibi)
caojie:addSkill(sk__zhixi)
Fk:loadTranslationTable{
  ["sk__caojie"] = "曹节",
  ["#sk__caojie"] = "",

  ["sk__huaibi"] = "怀璧",
  [":sk__huaibi"] = "锁定技，游戏开始时，或结束阶段，若你没有“玺”，你摸两张牌，然后将一张手牌置于武将牌上，称为“玺”。若你有“玺”，"..
  "其他角色使用的与之花色相同的【杀】和普通锦囊牌对你无效。",
  ["sk__zhixi"] = "掷玺",
  [":sk__zhixi"] = "出牌阶段限一次，你可以将“玺”交给一名其他角色，令其失去3点体力；若你已对其发动过〖掷玺〗，改为失去1点体力。",
  ["sk__caojie_xi"] = "玺",
  ["#sk__huaibi-card"] = "怀璧：将一张手牌置为“玺”",
  ["#sk__zhixi"] = "掷玺：将“玺”交给一名角色，令其失去3点体力！（若对其发动过则只失去1点体力）",

  ["$sk__huaibi1"] = "大汉之命，岂能落入你们的手中！",
  ["$sk__huaibi2"] = "想要玉玺，除非踏过我的身躯！",
  ["$sk__zhixi1"] = "逆臣篡汉，天不佑尔！",
  ["$sk__zhixi2"] = "你们，绝不会得到善终！",
  ["~sk__caojie"] = "不负君恩，无愧于民……",
}

return extension
